<template>
    <el-dialog v-model="isLogin" title="欢迎登录" width="500">
        <el-form ref="ruleFormRef" :rules="rules" :model="ruleForm">
            <el-form-item label="用户名：" prop="username" required>
                <el-input v-model="ruleForm.username" autocomplete="off" placeholder="请输入用户名"/>
            </el-form-item>
            <el-form-item label="密码：" prop="password" required>
                <el-input id="pwd1" type="password" v-model="ruleForm.password" autocomplete="off" placeholder="请输入密码"/>
                <el-icon style="position: absolute; left: 90%;color: seagreen;">
                    <template v-if="isEye"><View @click="toEye(1)"/> </template>
                    <template v-if="!isEye"><Hide @click="toEye(1)"/></template>
                </el-icon>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" style="width: 60%;" @click="submitForm(ruleFormRef)">登录</el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script setup lang="ts">
import { ref} from 'vue'
import { useRouter } from 'vue-router';
import type { FormInstance, FormRules} from 'element-plus'
import {ElMessage, ElLoading} from 'element-plus';
import {login,getUser} from '@/api/login';
import {useGlobStore} from '@/stores/useGlobStore'
import { storeToRefs} from 'pinia'

const store = useGlobStore();
const {isLogin} = storeToRefs(store);

const ruleFormRef = ref<FormInstance>()
const router = useRouter();
const isEye = ref(false);
const ruleForm = ref({
  password: '',
  username:''
})

const checkPassword = (rule: any, value: any, callback: any) => {
    if (value === '') 
    {
        callback(new Error('密码不能为空'))
    } 
    else if(value.length>12||value.length<5)
    {
        callback(new Error('密码长度为5-12位'))
    }
    else 
    {
        callback()
    }
}

const checkUsername = (rule: any, value: any, callback: any) => {
    if (value === '') 
    {
        callback(new Error('账号不能为空'))
    }
    else if(value.length>10)
    {
        callback(new Error('账号长度不能超过10位'))
    }
    else 
    {
        callback()
    }
}

const rules = ref<FormRules<typeof ruleForm>>({
  password: [{ validator: checkPassword, trigger: 'blur' }],
  username: [{ validator: checkUsername, trigger: 'blur' }],
})
//提交表单
const submitForm = (formEl: FormInstance | undefined) => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  store.setIsLogin(false);
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) 
    {
        login({username:ruleForm.value.username,password:ruleForm.value.password})
        .then((res)=>{
            console.log(res);
            if(String(res.data.code) === '200'){
                localStorage.setItem('psptToken',res.data.token);
                getUser().then((res:any)=>{
                    if(String(res.data.code) === '200')
                    {
                        console.log(res.data)
                        ElMessage({showClose: true,message: "操作成功",type: 'success'});
                        let user:{userType:string} = res.data.user;
                        if(res.data.dsUser!=null)
                        {
                          user.userType = res.data.dsUser.userType;
                        }
                        else user.userType = '1';
                        localStorage.setItem('dsUser',JSON.stringify(user));
                        store.setIsResh(true);
                        router.push('/');
                    }else{
                        ElMessage({showClose: true,message: '操作失败',type: 'error'});
                        console.log(res);
                    }
                }).catch((err:any)=>{console.log(err);})              
                }else{
                  ElMessage({
                    showClose: true,
                    message: '账号或密码错误',
                    type: 'error'
                  });
                  console.log(res);
                }
        }).catch((err:any)=>{console.log(err);})
    } else {
      ElMessage({
        showClose: true,
        message: '错误的提交',
        type: 'error'
      });
    }
  })
  loading.close();
}


function toEye(num:number)
{
  let doc = null;
  let is = false;
  if(num===1)
  {
    isEye.value = !isEye.value;
    is = isEye.value;
    doc = document.getElementById('pwd1')
  }
  if(is) 
  {
    doc!.setAttribute('type','text');
  }
  else
  {
    doc!.setAttribute('type','password');
  }
}
</script>

<style scoped>
.dialog-footer
{
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>